<template>
  <div>
    <span @click="openUserManage">用户管理</span>
    <!-- 用户管理弹框 -->
    <el-dialog
      v-model="userManageDialogVis"
      width="700"
      title="用户信息"
      class="dialogClass"
      draggable
      :modal="false"
      append-to-body
      :destroy-on-close="true"
      @close="closeUserManage"
    >
      <div class="container">
        <div class="header">
          <!-- 新增交通部门用户 -->
          <el-button :icon="CirclePlus" @click="openAddTrafficUser">
            新增
          </el-button>
          <!-- 新增交通部门用户弹框 -->
          <el-dialog
            v-model="addTrafUserDialogVis"
            title="新增交通部门用户"
            width="400"
            :modal="false"
            append-to-body
          >
            <el-form
              ref="addTrafUserFormRef"
              :model="addTrafUserForm"
              :rules="addTrafUserRules"
              label-width="100px"
            >
              <el-form-item label="用户名" prop="username">
                <el-input
                  v-model="addTrafUserForm.username"
                  placeholder="请输入用户名"
                  autocomplete="off"
                />
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input
                  v-model="addTrafUserForm.password"
                  placeholder="6位，由数字组成"
                  autocomplete="off"
                  show-password
                />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button
                  type="primary"
                  @click="confiAddTrafficUser(addTrafUserFormRef)"
                >
                  确认
                </el-button>
                <el-button @click="closeAddTrafficUser">取消</el-button>
              </span>
            </template>
          </el-dialog>
          <!-- 搜索用户 -->
          <el-input
            v-model="inputSearch"
            placeholder="搜索ID或用户名"
            :prefix-icon="Search"
          />
        </div>
        <!-- 所有用户表格 -->
        <el-table
          :data="
            tableData.slice(
              (currentPage - 1) * pageSize,
              currentPage * pageSize
            )
          "
          stripe
          border
          style="width: 100%"
          max-height="300"
        >
          <el-table-column prop="id" label="ID" width="110" sortable />
          <el-table-column prop="username" label="用户名" width="110" />
          <el-table-column label="用户类型" width="110">
            <template #default="scope">
              <el-tag
                :type="
                  scope.row.type === 'admin'
                    ? 'warning'
                    : scope.row.type === 'traffic'
                    ? 'success'
                    : ''
                "
              >
                {{
                  scope.row.type === "admin"
                    ? "管理员"
                    : scope.row.type === "traffic"
                    ? "交通部门"
                    : "普通用户"
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="isOnline" label="登录状态" width="110">
            <template #default="scope">
              <el-tag :type="scope.row.isOnline ? 'danger' : 'info'">
                {{ scope.row.isOnline ? "登录" : "下线" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <div v-if="scope.row.type !== 'admin'">
                <el-button size="small" @click="openUpdateUser(scope.row)"
                  >修改
                </el-button>
                <!-- 修改用户弹框 -->
                <el-dialog
                  v-if="isShowUpdateDialog === scope.row.id"
                  v-model="updateUserDialogVis"
                  title="修改用户信息"
                  width="400"
                  :modal="false"
                  append-to-body
                >
                  <el-form
                    ref="updateUserFormRef"
                    :model="updateUserForm"
                    :rules="updateUserRules"
                    label-width="100px"
                  >
                    <el-form-item label="用户名" prop="newUsername">
                      <el-input
                        v-model="updateUserForm.newUsername"
                        placeholder="请输入用户名"
                        autocomplete="off"
                      />
                    </el-form-item>
                    <el-form-item label="密码" prop="newPassword">
                      <el-input
                        v-model="updateUserForm.newPassword"
                        placeholder="6位，由数字组成"
                        autocomplete="off"
                        show-password
                      />
                    </el-form-item>
                  </el-form>
                  <template #footer>
                    <span class="dialog-footer">
                      <el-button
                        type="primary"
                        @click="confiUpdateUser(updateUserFormRef)"
                      >
                        确认
                      </el-button>
                      <el-button @click="closeUpdateUser">取消</el-button>
                    </span>
                  </template>
                </el-dialog>
                <!--  -->
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.row)"
                  >删除
                </el-button>
                <el-button
                  v-if="scope.row.isOnline"
                  size="small"
                  type="warning"
                  @click="handleLogout(scope.row)"
                  >强制下线
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页器 -->
      <template #footer>
        <div class="pagination">
          <el-pagination
            v-model:page-size="pageSize"
            v-model:current-page="currentPage"
            :page-sizes="[5, 7, 9, 10]"
            background
            :total="tableData.length"
            layout="total, sizes, prev, pager, next, jumper"
          />
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { UserHttp } from "../../../../request/UserHttp.js";
import { CirclePlus, Search } from "@element-plus/icons-vue";
import { mySort } from "../../../../utils/mySort";

// 分页器数据
const currentPage = ref(1);
const pageSize = ref(5);

// 表格数据
let tableData = ref([]);

// 公用 获取所有用户数据
let allUser = ref([]);
const userManaging = () => {
  // 后续有多次渲染数据，每次要先清空之前的数据
  allUser.value = [];
  // 设置查询参数
  let params = ["admin", "traffic", "common"];
  params.forEach(async (type) => {
    let resUsers = await UserHttp.getUserByTypeHttp(type);
    allUser.value = allUser.value.concat(resUsers.data.result);
    // 异步问题,导致得到的数据不能按照params中元素顺序来排序
    // mySort 照规定的顺序进行排序,admin traffic common
    mySort(allUser.value, ["admin", "traffic"], (item) => item.type);
    tableData.value = allUser.value;
    // console.log(tableData.value, 111);
  });
};

/* ===== 用户管理弹框 ===== */
const userManageDialogVis = ref(false);
const openUserManage = () => {
  // 获取用户
  userManaging();

  // 显示弹框
  userManageDialogVis.value = true;
};
const closeUserManage = () => {
  // 删除用户
  allUser.value = [];
  // 关闭弹框
  userManageDialogVis.value = false;
};

/* 表单规则 公用 */
const checkName = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入用户名"));
  } else {
    callback();
  }
};
const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    // 设置正则表达式 密码为6位数字
    let reg = /\d{6}/;
    let res = reg.test(value);
    if (!res) {
      callback(new Error("请输入6位数字"));
    } else {
      callback();
    }
  }
};

/* ===== 新增交通部门用户 ===== */
const addTrafUserDialogVis = ref(false);
//新增 表单数据
const addTrafUserFormRef = ref();
let addTrafUserForm = reactive({
  username: "",
  password: "",
  type: "traffic",
});
// 新增表单规则
const addTrafUserRules = reactive({
  username: [{ validator: checkName, trigger: "blur" }],
  password: [{ validator: validatePass, trigger: "blur" }],
});
// 打开新增交通用户弹框
const openAddTrafficUser = () => {
  addTrafUserDialogVis.value = true;
};
// 确认新增窘态用户 提交表单
const confiAddTrafficUser = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      // 表单验证 valid 有效
      // 进行注册.新增
      let resAddTraffic = await UserHttp.RegisterUserHttp(addTrafUserForm);
      //   console.log(resAddTraffic, 777);
      //   注册成功 用户类型为traffic
      if (resAddTraffic.data.code === 200) {
        ElMessage({
          message: "新增交通部门用户成功",
          type: "success",
        });
        // 关闭弹框
        addTrafUserDialogVis.value = false;
        // 重新渲染数据
        userManaging();
      } else {
        // 注册失败
        ElMessage.error("用户名重复,请重新输入");
      }
    } else {
      // 表单验证 valid 无效
      return false;
    }
  });
};
// 取消新增窘态用户，关闭新增交通用户弹框，清除表单数据
const closeAddTrafficUser = () => {
  addTrafUserDialogVis.value = false;
};

/* ===== 搜索用户 ===== */
let inputSearch = ref("");
watch(
  // 第一个参数 传入要侦听的值
  inputSearch,
  // 第二个参数 函数
  (newValue) => {
    if (newValue === "") {
      tableData.value = allUser.value;
      // console.log(tableData.value, 222);
    } else {
      // 执行搜索，获取搜索值，使用字符串匹配，遍历所有用户id和username
      tableData.value = allUser.value.filter((item) => {
        return (
          item.username.includes(inputSearch.value) ||
          String(item.id).includes(inputSearch.value)
        );
      });
      // console.log(tableData.value, 333);
    }
  }
);

/* ===== 修改用户 ===== */
// 整体所有弹框(该弹框为遍历得到，数量等于用户数长度)
const updateUserDialogVis = ref(false);
// 显示点击的用户的弹框 row.id
const isShowUpdateDialog = ref(null);
// 要进行修改的原始用户信息
const initUpdateUser = ref({});
//修改 表单数据
const updateUserFormRef = ref();
let updateUserForm = reactive({
  newUsername: "",
  newPassword: "",
});
// 修改 表单规则
const updateUserRules = reactive({
  newUsername: [{ validator: checkName, trigger: "blur" }],
  newPassword: [{ validator: validatePass, trigger: "blur" }],
});
// 打开修改用户弹框
const openUpdateUser = (row) => {
  // console.log(row, 88888);
  // 获取用户原始信息
  initUpdateUser.value = {
    username: row.username,
    password: row.password,
    type: row.type,
  };
  // 设置表单初始值
  updateUserForm.newUsername = row.username;
  updateUserForm.newPassword = row.password;
  // console.log(updateUserForm);
  // 打开弹框
  updateUserDialogVis.value = true;
  isShowUpdateDialog.value = row.id;
};
// 确认修改用户信息
const confiUpdateUser = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      // 表单验证 valid 有效
      let resUpdateUser = null;
      // 只修改密码 即原始用户名和表单用户名相等
      if (initUpdateUser.value.username === updateUserForm.newUsername) {
        let data = {
          username: initUpdateUser.value.username,
          password: initUpdateUser.value.password,
          newPassword: updateUserForm.newPassword,
          type: initUpdateUser.value.type,
        };
        resUpdateUser = await UserHttp.resetPassUserHttp(data);
        if (resUpdateUser.data.code !== 200) {
          ElMessage.error("修改用户信息失败");
        }
      } else {
        // 同时修改用户名和密码
        // 传参
        let params = initUpdateUser.value;
        // 新修改的数据
        let data2 = updateUserForm;
        // 进行修改
        resUpdateUser = await UserHttp.updateUserHttp(params, data2);
        if (resUpdateUser.data.code !== 200) {
          ElMessage.error("新用户名重复,请重新输入");
        }
      }
      // console.log(resUpdateUser, 777);
      //  修改成功
      if (resUpdateUser.data.code === 200) {
        ElMessage({
          message: "修改用户信息成功",
          type: "success",
        });
        // 关闭弹框
        updateUserDialogVis.value = false;
        // 重新渲染数据
        userManaging();
      }
    } else {
      // 表单验证 valid 无效
      return false;
    }
  });
};
// 关闭修改用户弹框 取消修改 清除修改表单数据
const closeUpdateUser = () => {
  updateUserDialogVis.value = false;
  // isShowUpdateDialog.value = null;
};

/* ===== 删除用户 ===== */
const handleDelete = (row) => {
  let type = row.type === "traffic" ? "交通部门" : "普通用户";
  ElMessageBox.confirm(
    `这是一个${type}的账号，删除可能导致该用户无法访问网站，是否确认要删除?`,
    "删除用户",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      let data = {
        username: row.username,
        type: row.type,
      };
      let resDelete = await UserHttp.deleteUserHttp(data);
      if (resDelete.data.code === 200) {
        // 重新渲染数据
        userManaging();
        ElMessage({
          message: "删除成功",
          type: "success",
        });
      } else {
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {});
};

/* ===== 强制下线 ===== */
const handleLogout = async (row) => {
  let data = {
    username: row.username,
    type: row.type,
  };
  let resLogout = await UserHttp.LogoutUserHttp(data);
  console.log(resLogout, 444);
  if (resLogout.data.code === 200) {
    // 重新渲染数据
    userManaging();
    ElMessage({
      type: "success",
      message: "强制下线成功",
    });
  }
};
</script>

<style lang="scss">
.dialogClass {
  //   margin: 0 !important;
  //   position: fixed !important;
  //   top: 70px;
  //   right: 20px;
  .el-dialog__body {
    padding: 10px;
    border-top: 1px #ddd solid;
  }
  .el-dialog__footer {
    display: flex;
    justify-content: space-between;
    padding-top: 0;
  }

  .container {
    // height: 295px;
    // min-height: 295px;
    // height: 340px;
    .header {
      display: flex;
      justify-content: space-between;
      .el-input {
        width: 250px;
      }
    }
    .el-table {
      margin-block: 10px;
      height: 249px;
    }
  }
}
</style>
